package com.ciwong.epaper.modules.epaper.dao;

import android.os.Handler;
import android.os.Looper;

import com.ciwong.epaper.R;
import com.ciwong.epaper.modules.bookstore.bean.PubLishClassBean;
import com.ciwong.epaper.modules.bookstore.bean.PublishWorkContent;
import com.ciwong.epaper.modules.epaper.bean.DeleteEP;
import com.ciwong.epaper.modules.epaper.util.UnicodeReader;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.utils.ThreadTask;
import com.ciwong.mobilelib.utils.ZipHelper;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * 电子报 相关业务Dao
 *
 * @author bin
 * @version ciwong v.1.0 2015/7/23 20:09
 * @since ciwong v.1.0
 */
public class EpaperDao {
    private static EpaperDao instance;

    private Handler mHandler;

    private EpaperDao() {
        mHandler = new Handler(Looper.getMainLooper());
    }

    /**
     * 获取唯一实例
     *
     * @return 唯一实例
     */
    public static EpaperDao getInstance() {
        if (instance == null) {
            syncInit();
        }
        return instance;
    }

    /**
     * 实例化对象
     */
    private static synchronized void syncInit() {
        if (instance == null) {
            instance = new EpaperDao();
        }
    }

    /**
     * 根据学校ID获取客服信息
     *
     * @param schoolId 学校ID
     * @param callBack 回调
     */
    public void getAdvisor(long schoolId, long brandId, BaseCallBack callBack) {
        EpaperRequest.getAdvisor(schoolId, brandId, callBack);
    }

    /**
     * 根据服务ID获取书籍
     *
     * @param schoolId  学校ID
     * @param serviceId 服务ID
     * @param page      页码
     * @param pageSize  每页条数
     * @param callBack  回调
     */
    public void getServiceBooks(long schoolId, int serviceId, int page,
                                int pageSize, BaseCallBack callBack) {
        EpaperRequest.getServiceBooks(schoolId, serviceId, page, pageSize,
                callBack);
    }

    /**
     * 根据品牌ID获取书籍
     */
    public void getEpageBookcase(int brandId, int pageIndex, int pageSize, BaseCallBack callBack) {
        EpaperRequest.getEpageBookcase(brandId, pageIndex, pageSize, callBack);
    }

    public void getGradeByBookCategoryId(int typeId, BaseExtCallBack callBack) {
        EpaperRequest.getGradeByBookCategoryId(typeId, callBack);
    }


    /**
     * 根据品牌ID获取书籍
     */
    public void getEpageBookcaseAll(int brandId, BaseCallBack callBack) {
        EpaperRequest.getEpageBookcaseAll(brandId, callBack);
    }

    /**
     * 根据服务ID、页码、页数获得书籍列表
     *
     * @param brandId
     * @param serviceIds
     * @param page
     * @param pageSize
     * @param callBack
     */
    public void getBookListByServiceID(int brandId, String serviceIds, int page, int pageSize,
                                       BaseCallBack callBack) {

        EpaperRequest.getBookListByServiceID(brandId, serviceIds, page, pageSize,
                callBack);
    }

    /**
     * 获取书籍目录
     *
     * @param packageId 资源包ID
     * @param cId       书籍目录ID(全部：-1)
     * @param tag       网络请求tag
     * @param callBack  回调
     */
    public void getBookCatalogue(String packageId, String userId, String cId, String mServiceId, Object tag,
                                 BaseCallBack callBack) {
        EpaperRequest.getBookCatalogue(packageId, userId, cId, mServiceId, tag, callBack);
    }

    /**
     * 获取章节资源
     *
     * @param packageId 资源包ID
     * @param cId       书籍目录ID(全部：-1)
     * @param tag       网络请求tag
     * @param callBack  回调
     */
    public void getCatalogueResourceList(String packageId, String cId, Object tag, boolean isFromDesk,
                                         BaseCallBack callBack) {
        EpaperRequest.getCatalogueResourceList(packageId, cId, tag, isFromDesk, callBack);
    }


    /**
     * 学生根据考生用书ID获取布置作业章节记录
     *
     * @param brandId
     * @param serviceId
     * @param packageId
     * @param callBack
     */
    public void getReceiveBookchapters(int brandId, int serviceId, String packageId, BaseCallBack callBack) {
        EpaperRequest.getReceiveBookchapters(brandId, serviceId, packageId, callBack);
    }


    public void getAdverts(int brandId, long userId, BaseCallBack callBack) {
        EpaperRequest.getAdverts(brandId, userId, callBack);
    }

    /**
     * 获取我的作业
     *
     * @param brandId  品牌ID
     * @param page     页码
     * @param pageSize 每页数量
     * @param workType 作业完成状态 ：0所有作业，1，未完成，2，已完成
     * @param callBack 回调
     */
    public void getMyWork(int brandId, int page, int pageSize, int workType, boolean isErrorWork,
                          BaseCallBack callBack) {
        EpaperRequest.getMyWork(brandId, page, pageSize, workType, isErrorWork, callBack);
    }

    public void getBookOrServiceList(int brandId, int page, int pageSize, int schoolId, int gradeId,
                                     int subjectId, int salesType, String area, String keyWords, final BaseCallBack callBack) {
        EpaperRequest.getBookOrServiceList(brandId, page, pageSize, schoolId, gradeId, subjectId, salesType, area, keyWords, callBack);
    }

    public void getBookOrServiceListByType(int brandId, int applyType, int page, int pageSize, int schoolId, int gradeId, int subjectId, String area, final BaseCallBack baseCallBack) {
        EpaperRequest.getBookOrServiceListByType(brandId, applyType, page, pageSize, schoolId, gradeId, subjectId, area, baseCallBack);
    }

    public void getSubjectListByGrade(int brandId, int gradeId, int salesType, String area, int schoolId, int applyType,
                                      final BaseCallBack callBack) {
        EpaperRequest.getSubjectListByGrade(brandId, gradeId, salesType, area, schoolId, applyType, callBack);

    }


    /**
     * 更新提交过的单元测试作业
     *
     * @param doWorkId 做作业ID
     * @param callBack 回调
     */
    public void updateUnitTestWork(final String doWorkId,
                                   final BaseCallBack callBack) {
        EpaperRequest.updateUnitTestWork(doWorkId, callBack);
    }

    /**
     * 读取SD卡中资源文件
     *
     * @param path     文件路径
     * @param callBack 回调
     */
    public void getResource(final String path, final BaseCallBack callBack) {
        ThreadTask.getInstance().executorDBThread(new Runnable() {
            @Override
            public void run() {
                File file = new File(path);
                if (!file.exists()) {
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (callBack != null) {
                                callBack.failed(R.string.file_no_exist);
                            }
                        }
                    });
                    return;
                }
                final StringBuffer sb = new StringBuffer();
                FileInputStream inputStream = null;
                BufferedReader br = null;
                try {
                    inputStream = new FileInputStream(file);
                    br = new BufferedReader(new UnicodeReader(inputStream,
                            Charset.defaultCharset().name()));
                    int maxBufferSize = 1 * 1024;
                    int available = inputStream.available();
                    int bufferSize = Math.min(available, maxBufferSize);
                    char[] buffer = new char[bufferSize];
                    int len = 0;
                    while ((len = br.read(buffer, 0, bufferSize)) != -1) {
                        // sb.append(EncodingUtils.getString(buffer, 0, len,
                        // "utf-8"));
                        sb.append(new String(buffer, 0, len));
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (callBack != null) {
                                callBack.failed(R.string.error_file);
                            }
                        }
                    });
                } finally {
                    try {
                        if (inputStream != null) {
                            inputStream.close();
                        }
                        if (br != null) {
                            br.close();
                        }
                    } catch (Exception e) {
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                if (callBack != null) {
                                    callBack.failed(R.string.error_file);
                                }
                            }
                        });
                        e.printStackTrace();
                    }
                }
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        CWLog.d("debug", "a1：" + sb);
                        if (callBack != null) {
                            callBack.success(sb.toString());
                        }
                    }
                });
            }
        }, ThreadTask.ThreadPeriod.PERIOD_HIGHT);
    }

    /**
     * 获取序列化本地资源
     *
     * @param type     序列化对象数组类型<br/>
     *                 方法: Type t = new TypeToken<List<自己类的名称>>(){}.getType();<br/>
     *                 or类的名称.class
     * @param callBack 回调
     */
    public void getSerializableObjects(final String path, final Type type,
                                       final BaseCallBack callBack) {
        getResource(path, new BaseCallBack() {

            @Override
            public void failed(Object data) {
                if (callBack != null) {
                    callBack.failed(data);
                }
            }

            @Override
            public void failed(int errorCode, Object data) {
                if (callBack != null) {
                    callBack.failed(errorCode, data);
                }
            }

            @Override
            public void success(Object data) {
                if (callBack != null) {
                    try {
                        Gson gson = new Gson();
                        Object obj = gson.fromJson(String.valueOf(data), type);
                        callBack.success(obj);
                    } catch (JsonSyntaxException e) {

                    } catch (Exception e) {
                        e.getStackTrace();
                    }


                }
            }
        });
    }

    /**
     * 读取SD卡中资源文件
     *
     * @param path 文件路径
     */
    public String getResource(final String path) {
        File file = new File(path);
        if (!file.exists()) {
            return "";
        }
        final StringBuffer sb = new StringBuffer();
        FileInputStream inputStream = null;
        BufferedReader br = null;
        try {
            inputStream = new FileInputStream(file);
            br = new BufferedReader(new UnicodeReader(inputStream,
                    Charset.defaultCharset().name()));
            int maxBufferSize = 1 * 1024;
            int available = inputStream.available();
            int bufferSize = Math.min(available, maxBufferSize);
            char[] buffer = new char[bufferSize];
            int len = 0;
            while ((len = br.read(buffer, 0, bufferSize)) != -1) {
                // sb.append(EncodingUtils.getString(buffer, 0, len,
                // "utf-8"));
                sb.append(new String(buffer, 0, len));
            }
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (br != null) {
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                return "";
            }
            return sb.toString();
        }
    }

    /**
     * 压缩文件
     *
     * @param uuid
     * @return
     */
    public String generateZipFile(String uuid) {
        // 生成zip包
        List<String> srcPaths = new ArrayList<String>();
        srcPaths.add(ESystem.getAnswersUuidPathNoCreate(uuid));
        String zipPath = srcPaths.get(0) + ".zip";
        final boolean isSuccess = ZipHelper.getInstance().addToZipTask(srcPaths,
                zipPath);
        CWLog.d("debug", "生成zip包:" + isSuccess);
        return isSuccess ? zipPath : null;
    }

    /**
     * 释放资源
     */
    public void release() {
        mHandler.removeCallbacksAndMessages(null);
        instance = null;
    }

    /**
     * 添加书籍到书柜记录
     */
    public void setBookcaseToServer(int brandId, String productId, int serviceId, BaseCallBack callBack) {
        EpaperRequest.setBookcaseToServer(brandId, productId, serviceId, callBack);
    }

    /**
     * 删除书柜记录By书箱ID
     */
    public void setDelBookcaseToServer(int brandId, String productId, int serviceId, BaseCallBack callBack) {
        EpaperRequest.setDelBookcaseToServer(brandId, productId, serviceId, callBack);
    }

    /**
     * 删除书柜记录By书箱ID
     */
    public void setDelBookcaseToServerByList(int brandId, ArrayList<DeleteEP> deleteEPList, BaseCallBack callBack) {
        EpaperRequest.setDelBookcaseToServerByList(brandId, deleteEPList, callBack);
    }


    /**
     * 获取视频讲解答案
     *
     * @param callBack 回调
     */
    public void getVideoExplainAnswer(String doWorkId, int requestType,
                                      final BaseCallBack callBack) {

        if (doWorkId != null) {
//            ModuleContent moduleContent = module.getResourceList().get(position);
            EpaperRequest.getVideoExplainAnswer(doWorkId, requestType, callBack);
        }

    }

    public void getOnlineAnswer(String doWorkId,
                                final BaseCallBack callBack) {
        if (doWorkId != null) {
            EpaperRequest.getOnlineAnswer(doWorkId, callBack);
        }
    }

    /**
     * 获取zip 包更新信息
     *
     * @param callBack 回调
     */
    public void getZipPackageUpdateInfo(String appVersion,
                                        BaseCallBack callBack) {
        EpaperRequest.getZipPackageUpdateInfo(appVersion, callBack);
    }

    /**
     * 复制一个目录及其子目录、文件到另外一个目录
     *
     * @param src
     * @param dest
     * @throws IOException
     */
    private void copyFolder(File src, File dest) throws IOException {

        if (src.isDirectory()) {
            if (!dest.exists()) {
                dest.mkdir();
            }
            String files[] = src.list();
            for (String file : files) {
                File srcFile = new File(src, file);
                File destFile = new File(dest, file);
                // 递归复制
                copyFolder(srcFile, destFile);
            }
        } else {
            InputStream in = new FileInputStream(src);
            OutputStream out = new FileOutputStream(dest);

            byte[] buffer = new byte[1024];

            int length;
            while ((length = in.read(buffer)) > 0) {
                out.write(buffer, 0, length);
            }
            in.close();
            out.close();
        }
    }

    public void getAutonomicStudyBooks(int brandId,
                                       BaseCallBack callBack) {
        EpaperRequest.getAutonomicStudyBooks(brandId, callBack);
    }

    public void getProductsbybookmark(int brandId, int bookmarkId, int pageIndex, int pageSize,
                                      BaseCallBack callBack) {
        EpaperRequest.getproductsbybookmark(brandId, bookmarkId, pageIndex, pageSize, callBack);
    }

    public void getDubbingVideoList(int gradeId, int pageIndex, int pageSize,
                                    BaseCallBack callBack) {
        EpaperRequest.getDubbingVideoList(gradeId, pageIndex, pageSize, callBack);
    }

    public void getDubVideoDetail(String versionId,
                                  BaseCallBack callBack) {
        EpaperRequest.getDubVideoDetail(versionId, callBack);
    }

    public void getDubbingVideoRecordList(int pageIndex, int pageSize,
                                          BaseCallBack callBack) {
        EpaperRequest.getDubbingVideoRecordList(pageIndex, pageSize, callBack);
    }

    public void setHeadLastBooks(String productId, int serviceId, int userId, int action,
                                 BaseCallBack callBack) {
        EpaperRequest.setHeadLastBooks(productId, serviceId, userId, action, callBack);
    }

    public void getBookDeskHomePage(int brandId, int gradeId,
                                    BaseCallBack callBack) {
        EpaperRequest.getBookDeskHomePage(brandId, gradeId, callBack);
    }

    public void getServiceProductsByIdClassids(int brandId, int isOwn, int mBookmarkId, int serviceId,String subCategoryId, String classIds, long schoolId, int gradeId, int bookType, String keyWords
            , int pageIndex, int pageSize, BaseExtCallBack callBack) {
        EpaperRequest.getServiceProductsByIdClassids(brandId, isOwn, mBookmarkId, serviceId,subCategoryId, classIds, schoolId, gradeId, bookType, keyWords, pageIndex, pageSize, callBack);
    }

    public void getGradeByBookmarkId(int brandId, int mBookmarkId, BaseExtCallBack callBack) {
        EpaperRequest.getGradeByBookmarkId(brandId, mBookmarkId, callBack);
    }

    public void getBookDeskCatalogue(String versionId,
                                     BaseCallBack callBack) {
        EpaperRequest.getBookDeskCatalogue(versionId, callBack);
    }

    /**
     * 获取评分系数
     */
    public void getScoreCoefficient(final BaseCallBack callBack) {
        EpaperRequest.getScoreCoefficient(callBack);
    }

    /**
     * 查询班级列表
     *
     * @param brandId
     * @param userRole
     * @param callBack
     */
    public void getMyClass(String brandId, int userRole, int schoolId, BaseCallBack callBack) {
        EpaperRequest.getMyClass(brandId, userRole, schoolId, callBack);
    }


    public void getmembers(int classId, String clientId, int getIntegral, int getVip, int role, BaseCallBack baseCallBack) {
        EpaperRequest.getmembers(classId, clientId, getIntegral, getVip, role, baseCallBack);
    }

    public void getPublishWorkRecords(int brandId, int workStatus, int classId, int checkDate, long startDate, long endDate, int page, int pageSize, BaseExtCallBack baseExtCallBack) {
        EpaperRequest.getPublishWorkRecords(brandId, workStatus, classId, checkDate, startDate, endDate, page, pageSize, baseExtCallBack);
    }

    public void getClassWorkRecords(int brandId, int page, int pageSize, BaseCallBack callBack) {
        EpaperRequest.getClassWorkRecords(brandId, page, pageSize, callBack);
    }

    public void getDkWorkRecords(int brandId, int page, int pageSize, int state, BaseExtCallBack baseExtCallBack) {
        EpaperRequest.getDkWorkRecords(brandId, page, pageSize, state, baseExtCallBack);
    }

    public void getServiceProductsByTop(int brandId, int isOwn, int pageIndex, int pageSize, int showPwd, int state,
                                        String wappid, BaseExtCallBack baseExtCallBack) {
        EpaperRequest.getServiceProductsByTop(brandId, isOwn, pageIndex, pageSize, showPwd, state, wappid, baseExtCallBack);
    }

    public void getResourceStatisticsWeb(String parentVersionId, String versionId, int moduleId, String resourceType, BaseCallBack baseCallBack) {
        EpaperRequest.getResourceStatisticsWeb(parentVersionId, versionId, moduleId, resourceType, baseCallBack);
    }

    public static void getPublishResources(String packageId, String cId, BaseCallBack callBack) {
        EpaperRequest.getPublishResources(packageId, cId, callBack);
    }


    public void publishWork(int brandId, int showAnswerMode, String publishUserName, String workName, int workType, int examMode,
                            int seeWorkMode, int submitMode, int showScoreMode, int abMode, int autoRefuseMode, int autoRefusePercent, int autoRefuseNum,
                            long completeDate, long sendDate, int workMessageType, int subjectId, int sourceType, String bookName, int publishType, int schoolId, String schoolName, String areaCode,
                            List<PubLishClassBean> classList, List<PublishWorkContent> contents, boolean isClassWork, BaseExtCallBack baseExtCallBack) {
        EpaperRequest.publishWork(brandId, showAnswerMode, publishUserName, workName, workType, examMode, seeWorkMode, submitMode, showScoreMode,
                abMode, autoRefuseMode, autoRefusePercent, autoRefuseNum, completeDate, sendDate, workMessageType, subjectId, sourceType,
                bookName, publishType, schoolId, schoolName, areaCode, classList, contents, isClassWork, baseExtCallBack);
    }

    public void listenSpeakExamination(String versionid, BaseCallBack baseCallBack) {
        EpaperRequest.listenSpeakExamination(versionid, baseCallBack);
    }

    public void followreadWordDetails(String versionid, BaseCallBack callBack) {
        EpaperRequest.followreadWordDetails(versionid, callBack);
    }

    public void getTeacherHead(int brandId, String serviceIds, BaseExtCallBack callBack) {
        EpaperRequest.getTeacherHead(brandId, serviceIds, callBack);
    }

    public void followreadTextParagraph(String versionId, BaseCallBack callBack) {
        EpaperRequest.followreadTextParagraph(versionId, callBack);
    }

    public void ListenSpeakExaminAtion(String versionId, BaseCallBack callBack) {
        EpaperRequest.ListenSpeakExaminAtion(versionId, callBack);
    }

    public void examinationData(String versionId, BaseCallBack callBack) {
        EpaperRequest.examinationData(versionId, callBack);
    }

    public void updateClassNameById(int classId, int periodId, int gradeId, String classAliasName, BaseCallBack callBack) {
        EpaperRequest.updateClassNameById(classId, periodId, gradeId, classAliasName, callBack);
    }

    public void addTeam(String teamname, int classId, String stustr, BaseCallBack callBack) {
        EpaperRequest.addTeam(teamname, classId, stustr, callBack);
    }

    public void editTeam(String teamname, int classId, String stustr, int teamId, BaseCallBack callBack) {
        EpaperRequest.editTeam(teamname, classId, stustr, teamId, callBack);
    }

    public void delTeam(int teamId, BaseCallBack callBack) {
        EpaperRequest.delTeam(teamId, callBack);
    }

    public void setUserBookTop(int istop, int productid, int serviceid, BaseCallBack callBack) {
        EpaperRequest.setUserBookTop(istop, productid, serviceid, callBack);
    }

    public void setEffectiveDate(long batchId, int state, long brandId, String wappid, long clientId, long effectiveDate, BaseCallBack callBack) {
        EpaperRequest.setEffectiveDate(batchId, state, brandId, wappid, clientId, effectiveDate, callBack);
    }

    public void setAutoRefusePercent(long batchId, int state, long brandId, String wappid, int autoRefusePercent, BaseCallBack callBack) {
        EpaperRequest.setAutoRefusePercent(batchId, state, brandId, wappid, autoRefusePercent, callBack);
    }

    public void getPublishbook(long userId, int brandId, int bookId, BaseCallBack callBack) {
        EpaperRequest.getPublishbook(userId, brandId, bookId, callBack);
    }

    public void checkServicePwd(String pwd, int state, int productId, int serviceId, String wappid, int brandId, BaseCallBack callBack) {
        EpaperRequest.checkServicePwd(pwd, state, productId, serviceId, wappid, brandId, callBack);
    }

    public void checkServiceCataloguesPwd(String pwd, String cId, int productId, int serviceId, BaseCallBack callBack) {
        EpaperRequest.checkServiceCataloguesPwd(pwd, cId, productId, serviceId, callBack);
    }

    public void getEpageServiceClassids(int isDefault, int sId, int uId, String classids, BaseCallBack callBack) {
        EpaperRequest.getEpageServiceClassids(isDefault, sId, uId, classids, callBack);
    }

    public void getFollowTeachers(int brandId, BaseCallBack callBack) {
        EpaperRequest.getFollowTeachers(brandId, callBack);
    }

    public void getFollowWorkRecords(int brandId, long teacherId, int page, int pageSize, BaseExtCallBack callBack) {
        EpaperRequest.getFollowWorkRecords(brandId, teacherId, page, pageSize, callBack);
    }

    public void getHeadAds(int brandId, BaseCallBack callBack) {
        EpaperRequest.getHeadAds(brandId, callBack);
    }

    public void getHeadBookMarkAds(int brandId, BaseCallBack callBack) {
        EpaperRequest.getHeadBookMarkAds(brandId, callBack);
    }

    public void setUserPassWord(int classId, int userId, String password, BaseExtCallBack baseCallBack) {
        EpaperRequest.setUserPassWord(classId, userId, password, baseCallBack);
    }
}
